﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Library.Bll;
using Library.Common;
using System.Text;
using System.Security.Cryptography;
using System.Data;

namespace HanhuaMicroCredit.Admin.Controllers
{
    public class SysMenuController : UserAuthenController //UserAuthenController
    {
        #region //路由地址转换
        private string getR(string controllers, string childFile, string menu, string page)
        {
            string _getr = "";
            string r = "~/Views/{0}/{1}/{2}";
            _getr = string.Format(r, controllers, childFile, page);
            if (menu != "")
            {
                r = "~/Views/{0}/{1}/{2}/{3}";
                _getr = string.Format(r, controllers, childFile, menu, page);
            }
            return _getr;
        }
        #endregion

        #region 通用访问

        public ActionResult Add(string menu, string name)
        {
            string page = "Add";
            if (name != "" && name != null)
                page = name;
            page += ".cshtml";
            return View(
                getR("SysMenu", menu, "", page)
                );
        }
        public ActionResult Edit(string menu, string tname, int id, string name)
        {
            string tbname = DencryptHelper.Decrypt(tname);
            Dictionary<string, object> d = CommonBLL.GetModel(tbname, "*", id);
            ViewData["id"] = id;
            ViewData["tname"] = tname;
            string page = "Edit";
            if (name != "" && name != null)
                page = name;
            page += ".cshtml";
            return View(
                getR("SysMenu", menu, "", page), d
                );
        }
        public ActionResult List(string menu, string name)
        {
            string page = "List";
            if (name != "" && name != null)
                page = name;
            page += ".cshtml";
            return View(
                getR("SysMenu", menu, "", page)
                );
        }

        #endregion

        #region //List菜单按钮

        /// <summary>
        /// 启用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ToolBan(string control, string node1, string node2, string tname)
        {
            string url = string.Format("/{0}/{1}/{2}", control, node1, node2);
            tname = DencryptHelper.Decrypt(tname);
            return Content(JUIResult.ReturnOpen(tname, url, "1"));
        }
        /// <summary>
        /// 禁用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ToolDel(string control, string node1, string node2, string tname)
        {
            string url = string.Format("/{0}/{1}/{2}", control, node1, node2);
            tname = DencryptHelper.Decrypt(tname);
            return Content(JUIResult.ReturnDel(tname, url, "1"));
        }

        #endregion


        #region post操作

        /// <summary>
        /// 添加用户(MD5加密密码)
        /// </summary>
        [HttpPost]
        public ContentResult AddUser(int? dtnum, string tname, string url, FormCollection fc)
        {
            #region //添加
            try
            {
                string arrName = DencryptHelper.Decrypt(tname);
                //
                Dictionary<string, object> d = new Dictionary<string, object>();
                foreach (string s in fc.Keys)
                {
                    if (s.IndexOf("t0_") > -1)
                    {
                        d.Add(s.Replace("t0_", ""), fc[s]);
                    }
                }
                //是否含有重复用户名
                if (d.ContainsKey("username"))
                {
                    bool b_username= CommonBLL.Exists(arrName, string.Format("UserName in ('{0}')", d["username"]));
                    if (b_username)
                    {
                        return Content(JUIResult.ResultMsg("用户名已存在"));
                    }
                }
                if (d.ContainsKey("password"))
                {
                    d["password"] = GetMD5(d["password"].ToString());
                }
                else
                {
                    return Content(JUIResult.ResultMsg("密码未设置"));
                }
                //主表添加
                if (!dtnum.HasValue)
                {
                    dtnum = 0;
                }
                Database database = (Database)dtnum.Value;
                int pId = CommonBLL.Add(database, arrName, d);
                //日志
                InsLogBll.InsertLog(arrName, "添加", "添加id:" + pId);

                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }


        /// <summary>
        /// 添加用户功能权限(1+2)
        /// </summary>
        [HttpPost]
        public ContentResult AddUserFunction(int? dtnum, string tname, string url, FormCollection fc)
        {
            #region //添加
            try
            {
                string arrName = DencryptHelper.Decrypt(tname);
                //
                Dictionary<string, object> d = new Dictionary<string, object>();
                foreach (string s in fc.Keys)
                {
                    if (s.IndexOf("t0_") > -1)
                    {
                        d.Add(s.Replace("t0_", ""), fc[s]);
                    }
                }
                if (d.ContainsKey("OperateLevel"))
                {
                    int sum = 0;
                    string[] strs=d["OperateLevel"].ToString().Split(',');
                    for (int i = 0; i < strs.Length; i++)
                    {
                        int o;
                        if (int.TryParse(strs[i], out o))
                        {
                            sum += 1 << o;
                        }
                    }
                    d["OperateLevel"] = sum.ToString();
                }
                
                //主表添加
                if (!dtnum.HasValue)
                {
                    dtnum = 0;
                }
                Database database = (Database)dtnum.Value;
                int pId = CommonBLL.Add(database, arrName, d);
                //日志
                InsLogBll.InsertLog(arrName, "添加", "添加id:" + pId);

                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }
        /// <summary>
        /// 用户功能权限
        /// </summary>
        [HttpPost]
        public ActionResult Userlevel(string v)
        {
            return PartialView("~/views/SysMenu/SysIBUserFunctions/UserLevel.ascx", v);
        }

        /// <summary>
        /// 角色权限
        /// </summary>
        [HttpPost]
        public ActionResult Rolelevel(string v)
        {
            return PartialView("~/views/SysMenu/UserRole/RoleTree.ascx", v);
        }
        /// <summary>
        /// 角色权限
        /// </summary>
        [HttpPost]
        public ActionResult Departlevel(string v)
        {
            return PartialView("~/views/SysMenu/UserDepart/RoleTree.ascx", v);
        }

        [HttpPost]
        public ActionResult SearchList(
            string tName,
            string pars,
            string name,
            string control,
            int pageindex,
            int pagesize,
            string dtnum,
            string states,
            string vd
            )
        {
            ViewData["vd"] = vd;
            #region //主附表关联查询
            List<string> compare = new List<string>();
            compare.Add("=");//__0
            compare.Add(">=");//__1
            compare.Add("<=");//__2
            compare.Add("like");//__3
            compare.Add("in");//__4
            compare.Add("not in");//__5
            //
            string[] arrName = DencryptHelper.Decrypt(tName).Split(',');
            string selectColumns = string.Format("{0}.*", arrName[0]);//可以放到页面


            string sortColumns = string.Format("{0}.id desc", arrName[0]);//可以放到页面
            //
            StringBuilder conditions = new StringBuilder();
            string isvalid = "1";
            if (states != "")
                isvalid = Utils.StrToInt(states, 0).ToString();
            else
                isvalid = "0,1";
            conditions.AppendFormat(" {0}.isValid in ({1}) ", arrName[0], isvalid);
            if (arrName.Length > 1)
            {
                //附表关联
                for (int i = 1; i < arrName.Length; i++)
                {
                    conditions.AppendFormat(" And {0}.id={1}.pId  ", arrName[0], arrName[i]);
                }
            }
            pars = HttpUtility.UrlDecode(pars);//
            string[] par = pars.Split(',');
            if (par.Length > 0)
            {
                List<string> l = new List<string>();
                foreach (string s in name.Split(','))
                    l.Add(s);
                int i = 0;
                foreach (string s in par)
                {
                    if (!Utils.StrIsNullOrEmpty(s))
                    {
                        string f = l[i];
                        int type = Utils.StrToInt(f.Substring(f.Length - 1, 1), 0);
                        string filed = f.Substring(2, f.Length - 5);
                        string forTable = arrName[Utils.StrToInt(f.Substring(0, 1), 0)];
                        string val = s.Trim();
                        val = HttpUtility.UrlDecode(val);
                        val = Utils.ChkSQL(val);
                        if (type == 3)
                        {
                            val = " '%" + val + "%'";
                        }
                        else if (type == 4 || type == 5)
                        {
                            val = val.Replace("_", ",");
                            val = "(" + val + ")";
                        }
                        else
                        {
                            val = " '" + val + "'";
                        }
                        conditions.AppendFormat(" And {0}.[{2}] {3} {1} ", forTable, val, filed, compare[type]);
                    }

                    i++;
                }
            }
            //
            PagedInfo p = new PagedInfo();
            p.PageSize = pagesize;
            p.PageIndex = pageindex;
            int database = Utils.StrToInt(dtnum, 1) - 1;
            PagedResult<DataSet> pR = CommonBLL.GetPagedList((Database)database, DencryptHelper.Decrypt(tName), selectColumns, sortColumns, conditions.ToString(), p);
            //
            return PartialView("~/Views/" + control + ".ascx", pR);
            #endregion
        }
        #endregion

        #region 菜单权限
        public ActionResult Permission(string v,string pid)
        {
            ViewData["id"] = v;
            ViewData["pid"] = pid;
            return View("~/Views/SysMenu/Roles/menu/list.aspx");
        }
        public ContentResult add_KM(string ids,string v,string pid)
        {
            try
            {
                string[] s_ids = ids.Split(',');
                if (ids.Length > 0)
                {
                    for (int i = 0; i < s_ids.Length; i++)
                    {
                        string condition=string.Format("Roleid={0} and Moduleid={1}", v, s_ids[i]);

                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("Roleid", v);
                        dic.Add("Moduleid", s_ids[i]);
                        dic.Add("Permission", 2);
                        dic.Add("ClassID", 1);
                        dic.Add("IBBigclss", "Sys_IBKMmenuTree");
                        List<Dictionary<string, object>> list_menu = CommonBLL.GetList("Sys_IBPermission", "id", "id desc",condition );
                        if (list_menu.Count <= 0)
                        {
                            int p_id = CommonBLL.Add("Sys_IBPermission", dic);
                        }
                        else
                        {
                            Dictionary<string,object> d_up=new Dictionary<string,object>();
                            d_up.Add("IsValid",1);
                            CommonBLL.Update("Sys_IBPermission", d_up, condition);
                        }
                    }
                    string rturl = "/SysMenu/Permission?v=" + v + "&pid=" + pid;
                    return Content(JUIResult.ResultUrl(rturl));
                }
                else
                {
                    return Content(JUIResult.ResultMsg("请选择数据"));
                }
                
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
        }
        public ContentResult del_KM(string ids, string v, string pid)
        {
            try
            {
                string[] s_ids = ids.Split(',');
                if (ids.Length > 0)
                {
                    for (int i = 0; i < s_ids.Length; i++)
                    {
                        string condition= string.Format("Roleid={0} and Moduleid={1}", v, s_ids[i]);
                        List<Dictionary<string, object>> list_menu = CommonBLL.GetList("Sys_IBPermission", "id", "id desc",condition);
                        if (list_menu.Count > 0)
                        {
                            int p_id = CommonBLL.Delete("Sys_IBPermission", condition);
                        }
                    }
                    string rturl = "/SysMenu/Permission?v=" + v + "&pid=" + pid;
                    return Content(JUIResult.ResultUrl(rturl));
                }
                else
                {
                    return Content(JUIResult.ResultMsg("请选择数据"));
                }

            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
        }
        #endregion

        /// <summary>
        /// 产生md5值
        /// </summary>
        /// <param name="sDataIn"></param>
        /// <returns></returns>
        private static string GetMD5(string sDataIn)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = System.Text.Encoding.UTF8.GetBytes(sDataIn);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string sTemp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
            }
            return sTemp.ToLower();
        }
    }
}
